package com.zzy.common.utils;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.zzy.common.config.MailProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * 功能描述: 邮箱
 *
 * @author zhouzhiyong
 * @date 2024/02/24 11:35
 */
@Component
public class EmailUtil {
    private final JavaMailSender javaMailSender;
    private final MailProperties mailProperties;

    @Autowired
    public EmailUtil(JavaMailSender javaMailSender, MailProperties mailProperties) {
        this.javaMailSender = javaMailSender;
        this.mailProperties = mailProperties;
    }
    private String from = "xiuheyouquan@guanmai.cn";
    //private String from = "lichuang@guanmai.cn";
    private String host = "smtp.exmail.qq.com";
    // 开启POP3/SMTP服务获取的授权码，不同于邮箱密码
    //private String password = "htWd63KWKy9wPpVT";
    private String password = "sa45zDmemdrF3p2M";
    private Integer port = 465;

    public void sendMail(String to, String title, String content) {
        MailAccount account = new MailAccount();
        account.setFrom(from);
        account.setUser(from);
        account.setHost(host);
        account.setPass(password);
        account.setPort(port);
        account.setSslEnable(true);
        MailUtil.send(account, to, title, content, false);
    }
    /**
     * 发送简单文本邮件的方法
     *
     * @param to      收件人邮箱地址，可以是多个收件人，用逗号分隔
     * @param subject 邮件主题
     * @param text    邮件正文内容
     */
    public void sendSimpleMail(String to, String subject, String text) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            // 设置发件人
            messageHelper.setFrom(mailProperties.getUsername());
            // 设置收件人，可以是多个收件人，以逗号分隔
            messageHelper.setTo(to.split(","));
            messageHelper.setSubject(subject);
            messageHelper.setText(text);
            // 设置邮件发送时间
            messageHelper.setSentDate(new Date());
            javaMailSender.send(mimeMessage);
            System.out.println("邮件发送成功");
        } catch (MessagingException e) {
            System.out.println("邮件发送失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
}
